<?php

!defined('IN_NOVA') && exit('Access Denied!');

class Data {

	public function start() {
		global $request;

		$action = $request->get( 'p' );

		switch( $action ) {
			case 'batch':
				$this->batch();
				break;
			case 'restoreexe':
				$this->restore_exe();
				break;
			default:
				$this->show( $action );
		}
	}

	private function batch() {
		global $db,$request;
		$backup_tables = array();
		$backup_tables = $request->get( 'table_arr','P','array' );
		$control = $request->get( 'Control','P' );
		$size = count( $backup_tables );
		if( $size == 0 ) {
			$this->show( 'backup', '您没有选中任何数据表', 'error' );
			return;
		}
		$back_file_name = 'XKLog_' . date( 'ymd', PHP_TIME ) . '_' . substr( md5( PHP_TIME ), -8) . '.sql';
		$db->query('SET SQL_QUOTE_SHOW_CREATE=0');
		$bakcontent = "# XKLog Data Backup File\n# Data Version: V" . XKLOG_DATA_VERSION . "\n# time: ".date('Y-m-d H:i', PHP_TIME)."\n# url: http://www.xklog.org\n#--------------------------------------\n\n";
		$bakcontent .= $this->table_backup( $backup_tables );
		$bakcontent .= $this->data_backup( $backup_tables );
		$back_file_path = APP_ROOT . 'data/' . $back_file_name;
		if( @file_put_contents( $back_file_path, $bakcontent ) ) {
			$this->show( 'backup', "数据备份完成，生成备份文件 $back_file_name", 'warning' );
		} else {
			$this->show( 'backup', '写入文件出错，请检查 data 目录是否存在以及是否有写入权限', 'error' );
		}
	}

	private function restore_exe() {
		$back_file = getGP( 'name','G' );
		data_restore( XKLOG_ROOT . 'data/' . $back_file );
		cache_load();
		show_admin_message( "数据导入完成", 'admin_data.php?action=Restore' );
	}

	private function table_backup( $backup_tables ) {
		global $db;
		$sql = '';
		foreach ( $backup_tables as $table ) {
			$row = $db->fetch_one_array("SHOW CREATE TABLE `$table`");
			$sql .= "DROP TABLE IF EXISTS `$table`;\n\n";
			$sql .= $row['Create Table'].";\n\n";
		}
		return $sql;
	}

	private function data_backup( $backup_tables ) {
		global $db;
		$table_num = count($backup_tables);
		$baksql = '';
		for ( $i = 0; $i < $table_num; $i ++ ) {
			// Online 表中的数据就不用备份了
			if( $backup_tables[$i] == strtolower( PREFIX_STR . 'Online' ) ) continue;
			$baksql .= "TRUNCATE TABLE `$backup_tables[$i]`;\n";
			$status = $db->fetch_one_array("SHOW TABLE STATUS LIKE '$backup_tables[$i]'");
			$rows = $status['Rows'];
			$query = $db->query("SELECT * FROM `" . $backup_tables[$i] . "`");
			$fields = $db->num_fields( $query );
			while ( $row = $db->fetch_array( $query,MYSQL_NUM ) ) {
				$baksql .= "INSERT INTO `$backup_tables[$i]` VALUES ('" . mysql_escape_string( $row[0] ) . "'";
				for ( $j = 1; $j < $fields; $j++) {
					$baksql .= " ,'" . mysql_escape_string( $row[$j] ) . "'";
				}
				$baksql .= ");\n";
			}
			$db->free_result($query);
		}
		return $baksql;
	}

	private function data_restore( $back_file ) {
		global $db;
		$query = '';
		$baksql = file( $back_file );
		foreach ($baksql as $ikey => $val) {
			$val = trim($val);
			if (!$val || substr($val,0,1) == '#') continue;
			if ( eregi('\;$', $val) ) {
				$query .= $val;
				if ( eregi('^CREATE',$query) ) {
					$query = substr($query, 0, strrpos($query, ')')+1);
					if( $db->version() > '4.1' ){
						$query .= 'ENGINE=MyISAM DEFAULT CHARSET=utf8;';
					} else {
						$query .= 'TYPE=MyISAM;';
					}
				} elseif ( eregi('^INSERT', $query) ) {
					$query = 'REPLACE '.substr($query,6);
				}
				$db->query($query);
				$query = '';
			} else {
				$query .= $val;
			}
		}
	}

	private function show( $action, $message = '', $type = '' ) {
		global $cache;
		if( $message != '' ) {
			$message = '<p class="' . $type . '">' . $message . '</p>';
		}
		@header("content-type: text/html; charset=utf-8");
?>
<div class = "admin_panel">
	<div class = "admin_title"> 数据管理</div>
	<div class = "admin_content">
		<?php
		echo $message;
		switch( $action ) {
			case 'backup':
				$this->backup();
				break;
			case 'restore':
				$this->restore();
				break;
			case 'check':
				$this->check();
				break;
			default:
				$this->main();
		}
		?>
		<div class="main_button"></div>
	</div>
</div>
<?php
	}

	private function backup() {
		global $db;
		$query = $db->query("SHOW TABLE STATUS");
		$prelen = strlen( DB_PREFIX );
		$sys_tables = $other_tables = array();
		while ( $row = $db->fetch_array($query) ) {
			$aname = substr($row['Name'],0,$prelen) == strtolower( DB_PREFIX ) ? 'sys_tables' : 'other_tables';
			${$aname}[] = array(
			'name' => $row['Name'],
			'rows' => $row['Rows'],
			'size' => $row['Data_length'] + $row['Index_length']
			);
		}
?>
			<form name="smslist" action="index.php?m=data&p=batch" method="post">
				<div style="padding:5px;margin:2px;">      
					<table class="pickme" style="table-layout: fixed;word-wrap: break-word;" width="100%" border="0" cellpadding="0" cellspacing="1" bgcolor="#bbbbbb">
						<thead>
							<tr align="center" height="22" bgcolor="#ffffff">
								<td width="3%"><input type="checkbox" name="allbox" onclick="CheckAll();"><input type="checkbox" id="ckbox" style="display:none;" disabled></td>
								<td width="4%">序号</td>
								<td width="29%">表名</td>
								<td width="35%">记录数</td>
								<td width="29%">大小</td>
							</tr>
						</thead>
						<tbody>
							<?php
							for ($i = 0; $i < count( $sys_tables ) ; $i ++) {
							?>
							<tr align="center" height="20" bgcolor="#ffffff">
								<td><input type="checkbox" id="ckbox" name="table_arr[]" value="<?php echo $sys_tables[$i]['name'] ?>" /></td>
								<td><?php echo $i+1 ?></td>
								<td style="text-align:left;padding-left:10px;"><?php echo $sys_tables[$i]['name'] ?></td>
								<td><?php echo $sys_tables[$i]['rows'] ?> 条</td>
								<td>
								<?php
								if( $sys_tables[$i]['size'] < 1024 ){
									echo $sys_tables[$i]['size'] . 'B';
								}elseif( $sys_tables[$i]['size'] < 1024*1024 ) {
									echo round( $sys_tables[$i]['size']/1024, 2 ) . 'KB';
								}else{
									echo round( $sys_tables[$i]['size']/(1024*1024), 2 ) . 'MB';
								}
								?>
								</td>
							</tr>
							<?php
							}
							?>
						<tbody>
					</table>
				</div>
				<div align="center">批量管理选项: <input type="radio" name="Control" value="备份" checked="checked"/>备份 <input type="submit" name="functionmit" class="main_button" value="执行操作" /></div>
			</form>
<?php
	}

	private function restore() {
		$file_arr = array();
		$data_path = APP_ROOT . 'data/';
		$handle = opendir( $data_path );
		while ( ( $each_file = readdir( $handle ) ) !== false ) {
			if ( $each_file != '.' && $each_file != '..' && end( explode( '.', $each_file ) ) == 'sql' ) {
				$fp = fopen( $data_path . $each_file, 'rb');
				$back_info = fread($fp, 200);
				fclose($fp);
				$back_info = explode("\n", $back_info);
				$file_arr[] = array( 'name' => $each_file, 'size' => filesize( $data_path . $each_file ), 'version' => substr( $back_info[1], 17 ), 'time' => substr( $back_info[2],8 ) );
			}
		}
		closedir( $handle );
?>
<div style="padding:5px;margin:2px;">      
	<table style="table-layout: fixed;word-wrap: break-word;" width="100%" border="0" cellpadding="0" cellspacing="1" bgcolor="#bbbbbb">
		<thead>
			<tr align="center" height="22" bgcolor="#ffffff">
				<td width="3%"></td>
				<td width="4%">序号</td>
				<td width="29%">文件名</td>
				<td width="15%">数据版本</td>
				<td width="18%">备份时间</td>
				<td width="18%">文件大小</td>
				<td width="13%">管理操作</td>
			</tr>
		</thead>
		<tbody>
		<?php
			for ($i = 0; $i < count( $file_arr ) ; $i ++) {
		?>
			<tr align="center" height="20" bgcolor="#ffffff">
				<td></td>
				<td><?php echo $i+1 ?></td>
				<td style="text-align:left;padding-left:10px;"><?php echo $file_arr[$i]['name'] ?></td>
				<td><?php echo $file_arr[$i]['version'] ?></td>
				<td><?php echo $file_arr[$i]['time'] ?></td>
				<td>
				<?php
				if( $file_arr[$i]['size'] < 1024 ){
					echo $file_arr[$i]['size'] . 'B';
				}elseif( $file_arr[$i]['size'] < 1024*1024 ) {
					echo round( $file_arr[$i]['size']/1024, 2 ) . 'KB';
				}else{
					echo round( $file_arr[$i]['size']/(1024*1024), 2 ) . 'MB';
				}
				?>
				</td>
				<td>
					<span class="Control">
					<img src="include/edt.gif" width="16" height="16" /><a href="index.php?m=data&p=rstoreexe&name=<?php echo $file_arr[$i]['name'] ?>">导入</a>
					</span>
				</td>
			</tr>
			<?php
				}
			?>
		</tbody>
	</table>
</div>
<?php
	}

	private function main() {
?>
			<div style="padding:10px;">
				欢迎进行 <b>数据管理</b>，在这里您可以备份当前的数据，也可以恢复以前的数据。
			</div>
<?php
	}

	private function check() {
?>
<div style="padding:10px;">
	<a href="index.php?m=set&p=rebuildexe">重建系统缓存</a><br />
	<a href="index.php?m=category&p=datacheckexe">重新统计分类数据</a><br />
	<a href="index.php?m=article&p=datacheckexe"><?php echo L('_COMMENT_DATA_CHECK_'); ?></a><br />
	<a href="index.php?m=article&p=tagdatacheckexe"><?php echo L('_TAG_DATA_CHECK_'); ?></a>
</div>
<?php
	}
}
?>
